<?php
header("content-type:text/html;charset=utf-8;");
include(dirname(__DIR__).'/Common/Fpage.class.php');
class Category extends Fpage{
	protected $db;
	protected $tab;
	protected $pid;
	protected $name;
	protected $img;
	public function __construct($db,$tab='goods_category',$size=1,$nums=5){
		$this->db=$db;
		$this->tab=$tab;
		parent::__construct($db,$tab,$size,$nums);		
	}
	//检验表单数据
	public function checkForm(){
		$this->pid=$_POST['pid'];
		$this->name=$_POST['categoryName'];
		$this->img=htmlspecialchars($_POST['thumbImg']);
		if(empty($this->name)){return array('code'=>102,'msg'=>"请输入分类名称！",'data'=>'') ;exit;}
	}
	//将分类加入数据库
	public function addCategory(){
		$sql="insert into {$this->tab}(pid,name,img) values('{$this->pid}','{$this->name}','{$this->img}')";
		if($this->db->otherData($sql)>0){
			return array('code'=>104,'msg'=>"添加分类成功！",'data'=>'') ;exit;
		}else{
			return array('code'=>103,'msg'=>"添加分类失败！",'data'=>'') ;exit;
		};
	}
	//选取全部分类内容
	public function getAllCategory(){
		$sql="select * from {$this->tab}";	
		return $this->db->selectRows($sql);
	}

	//根据name 更新分类名
	public function updateCategoryName($oldId,$newName){
		if(empty($newName)){ return array('code'=>118,'msg'=>"分类名不能为空！") ;exit;}
		$sql="update {$this->tab} set  name='{$newName}'  where id={$oldId}"; 
		$res=$this->db->otherData($sql);
		if($res>0){
			return array('code'=>119,'msg'=>"修改分类名成功！") ;exit;
		}else{
			return array('code'=>120,'msg'=>"修改分类名失败！") ;exit;
		}
	}

	public function findNameById($id){
		$sql="select name from {$this->tab} where id={$id}"; 
		$res=$this->db->selectRow($sql);
		return $res['name'];
	}
	public function deleteById($id){
		$res=array('code'=>105,'msg'=>"删除分类失败！",'data'=>'') ;
		$sql="select id from {$this->tab} where pid='{$id}' ";
		if($this->db->selectRow($sql)){
			$res=array('code'=>107,'msg'=>"请先删除子分类！",'data'=>'') ;
		}else{
			$sql="delete from {$this->tab} where id={$id}";
			if($this->db->otherData($sql)>0){
				$res=array('code'=>106,'msg'=>"删除分类成功！",'data'=>'') ;
			}
		}

		return $res;
	}	

}//类结束
